<template>
  <div class="short-message-content">
    <el-form
      ref="smsForm"
      :model="formData"
      label-position="top"
      :rules="rules"
    >
      <el-form-item prop="sign.id" label="签名">
        <el-select
          v-model="formData.sign"
          style="width: 100%"
          clearable
          filterable
          value-key="id"
        >
          <el-option
            v-for="item in autographList"
            :key="item.id"
            :label="item.displayName"
            :value="{
              id: item.id,
              name: item.displayName,
            }"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="template.id" label="模板">
        <el-select
          v-model="formData.template"
          style="width: 100%"
          clearable
          filterable
          value-key="id"
          @change="changeTemplet"
        >
          <el-option
            v-for="item in templetList"
            :key="item.id"
            :label="item.displayName"
            :value="{
              id: item.id,
              content: item.content,
            }"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        v-show="type === 'singleSend'"
        prop="phone"
        label="手机号"
        :rules="{
          required: true,
          trigger: 'blur',
          validator: validNum,
        }"
      >
        <el-input
          placeholder="请输入手机号码"
          v-model.trim="formData.phone"
          clearable
        />
      </el-form-item>
      <el-form-item
        v-show="type === 'batchSend'"
        prop="phone"
        label="手机号"
        :rules="{
          required: true,
          trigger: 'blur',
          validator: validNum,
        }"
      >
        <el-input
          :rows="4"
          type="textarea"
          placeholder="最多可向500个手机号码发送同样内容的短信，号码间用英文逗号,分隔，群发会有一定的延迟，请以发送记录为准"
          v-model.trim="formData.phone"
          clearable
        />
      </el-form-item>
    </el-form>
    <div class="content">
      <span v-show="formData.sign.name">
        {{ "【" + formData.sign.name + "】" }}
      </span>
      <template v-if="formData.template.id">
        <div v-for="(item, index) in templetArr" :key="index">
          <el-input
            v-if="index % 2 === 1"
            v-model="paramMap[templetArr[index]]"
          ></el-input>
          <span v-else>{{ item }}</span>
        </div>
      </template>
      <p class="word-num">
        (<span
          :class="{
            'limit-color':
              type === 'singleSend'
                ? singleWordNum > 1000
                : batchWordNum > 1000,
          }"
          >{{ type === "singleSend" ? singleWordNum : batchWordNum }}</span
        >
        / 1000)
      </p>
    </div>
    <div class="btns">
      <el-button size="mini" @click="close">关闭</el-button>
      <el-button size="mini" @click="reset">重置</el-button>
      <el-button
        :type="
          type === 'singleSend'
            ? singleWordNum > 1000
              ? 'info'
              : 'primary'
            : batchWordNum > 1000
            ? 'info'
            : 'primary'
        "
        :disabled="
          type === 'singleSend' ? singleWordNum > 1000 : batchWordNum > 1000
        "
        size="mini"
        @click="sendSms"
        >发送</el-button
      >
    </div>
  </div>
</template>
<script lang="ts">
import { Component, Vue, Prop, Watch } from 'vue-property-decorator'
import { v4 as uuidv4 } from 'uuid'
import { commonAction, deepClone } from '@/utils/common'
import { CommonModule } from '@/store/modules/common'
import { isNumber2 } from '@/utils/validate'
@Component({
  name: 'shortMessageContent'
})
export default class SendShortMessage extends Vue {
  [x: string]: any
  @Prop() private type
  @Prop({ default: () => [] }) private autographList
  @Prop({ default: () => [] }) private templetList
  private formData: any = {
    sign: {
      id: '',
      name: ''
    },
    template: {
      id: '',
      content: ''
    },
    phone: ''
  }

  private templetArr: any = []

  private singleWordNum: any = 0 // 单个发送

  private batchWordNum: any = 0 // 群发

  private paramMap: any = {}

  private rules: any = {
    'sign.id': [{ required: true, message: '请选择签名', trigger: 'change' }],
    'template.id': [{ required: true, message: '请选择模板', trigger: 'change' }]
  }

  private validNum (rule: any, value: string, callback: any) {
    if (this.type === 'singleSend') { // 单个发送
      if (!isNumber2(value)) {
        callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    } else { // 群发
      if (value.indexOf(',') > -1) {
        const phonesArr = value.split(',')
        if (phonesArr.some((item, index) => item === phonesArr[index + 1])) {
          callback(new Error('手机号不能重复'))
        } else {
          callback()
        }
      } else {
        if (!isNumber2(value)) {
          callback(new Error('请输入正确的手机号'))
        } else {
          callback()
        }
      }
    }
  }

  public clearFormValid () {
    (this.$refs as any).smsForm.clearValidate()
  }

  private changeTemplet (val) {
    this.templetArr = [] // 清空数据
    this.paramMap = {}
    let idx = 0
    if (val.content && /\$\{.*?\}/.test(val.content)) { // 模板中有变量
      const wordArr = val.content.split(/\$\{.*?\}/) // 用变量分隔模板
      val.content = val.content.replace(/\$\{(.*?)\}/g, (v, mv) => {
        this.templetArr.push(wordArr[idx++], mv) // 匹配变量并吧变量key加入数组中
        return ''
      })
      this.templetArr.push(wordArr[wordArr.length - 1]) // 分割最后一项加入数组中
    } else {
      this.templetArr.push(val.content)
    }
  }

  get getParamNum () {
    let paramNum = 0
    if (Object.keys(this.paramMap).length) {
      Object.keys(this.paramMap).forEach(v => {
        paramNum += this.paramMap[v].length
      })
    }
    return paramNum
  }

  get wordTotal () {
    let num = 0
    if (this.formData.sign.id && this.formData.template.id) { // 签名、模板都存在
      num = (this.formData.sign.name.length + this.formData.template.content.length + 2 + this.getParamNum) || 0 // 2 签名【】长度
    } else if (!this.formData.sign.id && this.formData.template.id) { // 模板存在、签名不存在
      num = (this.formData.template.content.length + this.getParamNum) || 0
    } else if (this.formData.sign.id && !this.formData.template.id) { // 签名存在、模板不存在
      num = (this.formData.sign.name.length + 2) || 0
    } else { // 模板、签名都不存在
      num = 0
    }
    return num
  }

  get getAccountId () {
    return (CommonModule as any).session.user.accountId || ''
  }

  @Watch('wordTotal')
  private changeWordNum (val) {
    if (this.type === 'singleSend') {
      this.singleWordNum = val
    } else {
      this.batchWordNum = val
    }
  }

  public clearContent () {
    this.formData = {
      sign: {
        name: '',
        id: ''
      },
      template: {
        id: '',
        content: ''
      },
      phone: '',
      content: ''
    }
    this.templetArr = []
  }

  private getUUID () {
    return uuidv4().replace(/-/g, '')
  }

  private sendSms () {
    (this.$refs.smsForm as any).validate(valid => {
      if (valid) {
        let url = ''
        const paramData: any = {}
        if (this.type === 'batchSend') {
          url = '/sms-api/sms/api/sms/send-same'
          paramData.phones = this.formData.phone.split(',')
        } else {
          url = '/sms-api/sms/api/sms/send-one'
          paramData.phone = this.formData.phone
        }
        // 发送短信
        const params = {
          url,
          method: 'POST',
          data: {
            requestId: this.getUUID(),
            action: 'API_SMS_SEND',
            param: {
              account: this.getAccountId,
              ...paramData,
              template: this.formData.template.id,
              sign: this.formData.sign.id,
              paramMap: this.paramMap // 模板参数：值
            }
          }
        }
        commonAction(params).then(res => {
          if (res.code === '0000200') {
            this.$message.success('发送成功')
            this.close()
            this.reset()
          }
        })
      }
    })
  }

  private close () {
    this.$emit('closePop')
  }

  private reset () {
    this.$emit('resetCont')
  }
}
</script>
<style lang="stylus" scoped>
.short-message-content
  .btns
    text-align right
    margin-top 20px
  .limit-color
    color #F99A93
  >>> .el-form-item
    margin-bottom 10px !important
    .el-form-item__label
      display inline !important
  .content
    margin-top 20px
    display flex
    align-items center
    flex-wrap wrap
    background #F3F6F9
    padding 20px 20px 40px
    position relative
    .word-num
      color #B3B9C7
      position absolute
      bottom 10px
      right 10px
    >>> input
      width 100px
      border none
      border-bottom 1px solid #999
      text-align center
      border-radius 0
      &.el-input__inner
        background-color #F3F6F9
</style>
